import { eq } from 'drizzle-orm'
import { usersTable } from '~~/server/db/schema/user'
import { db } from '~~/server/db'

export default defineEventHandler(async (event) => {
  const id = Number(getRouterParam(event, 'id'))

  if (!id || isNaN(id)) {
    throw createError({
      statusCode: 400,
      message: '用户ID格式错误'
    })
  }

  try {
    const [user] = await db
      .select({
        id: usersTable.id,
        phone: usersTable.phone,
        role: usersTable.role,
        status: usersTable.status,
        lastLoginAt: usersTable.lastLoginAt,
        createdAt: usersTable.createdAt,
        updatedAt: usersTable.updatedAt
      })
      .from(usersTable)
      .where(eq(usersTable.id, id))
      .limit(1)

    if (!user) {
      throw createError({
        statusCode: 404,
        message: '用户不存在'
      })
    }
    setResponseStatus(event, 200)
    return {
      data: user
    }
  } catch (error: any) {
    if (error.statusCode === 404) {
      throw error
    }
    console.error('Get user detail error:', error)
    throw createError({
      statusCode: 500,
      message: '获取用户详情失败'
    })
  }
})
